<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 求解方程 -->
    <script>
      let coefficient = 0 //x的系数
      let value = 0
      var solveEquation = function (equation) {
        //全局变量置零，要不然后台多个连续用例过不了
        coefficient = 0
        value = 0
        //等号左边一组，等号右边一组
        let array = equation.split('=')
        parse(array[0], 1)
        parse(array[1], -1)
        if (coefficient == 0) return value == 0 ? 'Infinite solutions' : 'No solution'
        else return 'x=' + -value / coefficient
      }
      var parse = function (str, sign) {
        i = 0
        curSign = 1
        while (i < str.length) {
          //处理单个x
          if (str[i] == 'x') {
            coefficient += sign * curSign
            i++
          }
          //处理+号，改变下一次运算的正负标识符curSign
          else if (str[i] == '+') {
            curSign = 1
            i++
          }
          //处理-号，改变下一次运算的正负标识符curSign
          else if (str[i] == '-') {
            curSign = -1
            i++
          }
          //处理数字
          else {
            let num = 0
            //循环遍历所有数字并且存储
            while (i < str.length && !isNaN(Number(str[i]))) {
              num = num * 10 + Number(str[i])
              i++
            }
            //当数字后面是x时
            if (str[i] == 'x') {
              coefficient += num * curSign * sign
              i++
            }
            //当数字后面时+或者-时
            else value += num * curSign * sign
          }
        }
      }
      // console.log(solveEquation('x+5-3+x=6+x-2'))
      // console.log(solveEquation('x=x'))
      console.log(solveEquation('2x=x'))
    </script>
  </body>
</html>
